package com.voute.View.Fragement;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.voute.App.App;
import com.voute.Base.BaseFragment;
import com.voute.Model.Action.DisappearAction;
import com.voute.Model.Bean.DiscoveryBean;
import com.voute.Model.Bean.DiscoveryFeed;
import com.voute.Presenter.IDiscoveryPresenter;
import com.voute.Presenter.Impl.DiscoveryPresenterImpl;
import com.voute.R;
import com.voute.Utils.PreferenceUtils;
import com.voute.View.Adapter.DiscoveryAdapter;
import com.voute.View.IView.IDiscoveryView;

import java.util.ArrayList;

/**
 * 今日热门排行Fragment
 * Created by liukanshan on 2016/12/9.
 */

public class DiscoveryFragment extends BaseFragment implements IDiscoveryView {

    private SwipeRefreshLayout swipe_refresh;
    private ListView content_list;
    private IDiscoveryPresenter presenterImpl;
    private DiscoveryAdapter discoveryAdapter;
    private ArrayList<DiscoveryFeed> entities = new ArrayList<>();
    private String anchor = "0";
    private boolean stopLoadMore;
    private boolean isLoading;
    private boolean isRefresh = true;
    private int distance = 0;
    private String type = "circle";
    private TextView no_data_desc;
    private RelativeLayout notice_layout;
    private TextView tv_close_notice;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_discovery;
    }

    @Override
    public void setupView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getString("feed_type", "circle");
        }
        swipe_refresh = $(R.id.swipe_refresh);
        no_data_desc = $(R.id.no_data_desc);
        tv_close_notice=$(R.id.tv_close_notice);
//        bottom_query_float_btn = $(R.id.bottom_query_float_btn);
//        if (type.equals("discovery")) {
//            bottom_query_float_btn.setVisibility(View.GONE);
//        }
        swipe_refresh.setColorSchemeColors(Color.parseColor("#0f88eb"));
        content_list = $(R.id.content_list);
        swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//              setupData();
                getData();
            }
        });
        notice_layout = $(R.id.notice_layout);
        discoveryAdapter = new DiscoveryAdapter(getActivity()
                , entities);
        content_list.setAdapter(discoveryAdapter);
        swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                getPageDiscoveryFeeds(isRefresh);
            }
        });

        content_list.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int last_visiable = absListView.getLastVisiblePosition();
                if (!stopLoadMore && !isLoading && (last_visiable > 0)) {
                    if (last_visiable + 2 > totalItemCount) {
                        isRefresh = false;
                        getPageDiscoveryFeeds(isRefresh);
                    }
                }
                if (type.equals("circle")) {
                    int dy = getScrollY();
                    if (dy - distance > 50) {
                        distance = dy;
//                        bottom_query_float_btn.setVisibility(View.GONE);
                    } else if (dy - distance < -50) {
                        distance = dy;
//                        bottom_query_float_btn.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
//        bottom_query_float_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                Intent intent = new Intent(DiscoveryFragment.this.getActivity(), QueryActivity.class);
//                Intent intent = new Intent(DiscoveryFragment.this.getActivity(), SearchActivity.class);
//                DiscoveryFragment.this.getActivity().startActivity(intent);
//            }
//        });
        tv_close_notice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notice_layout.setVisibility(View.GONE);
                if (!"circle".equals(type)) {
                    if (TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
                        notice_layout.setVisibility(View.GONE);
                        App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).edit().putBoolean("default_should_show_notice", false).commit();
                    } else {
                        notice_layout.setVisibility(View.GONE);
                        App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).edit().putBoolean(PreferenceUtils.GetUserIdHash() + "_should_show_notice", false).commit();
                    }
                }
            }
        });
        notice_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notice_layout.setVisibility(View.GONE);
                if (!"circle".equals(type)) {
                    if (TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
                        notice_layout.setVisibility(View.GONE);
                        App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).edit().putBoolean("default_should_show_notice", false).commit();
                    } else {
                        notice_layout.setVisibility(View.GONE);
                        App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).edit().putBoolean(PreferenceUtils.GetUserIdHash() + "_should_show_notice", false).commit();
                    }
                }
            }
        });
    }

    public void onEvent(DisappearAction action){
//        if(!"circle".equals(type)){
//            if (TextUtils.isEmpty(PreferenceUtils.GetUserIdHash())) {
//                notice_layout.setVisibility(View.GONE);
//                App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).edit().putBoolean("default_should_show_notice", false).commit();
//            } else {
//                notice_layout.setVisibility(View.GONE);
//                App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).edit().putBoolean(PreferenceUtils.GetUserIdHash() + "_should_show_notice",false).commit();
//            }
//        }
    }

    @Override
    public void setupData() {
//        presenterImpl = new DiscoveryPresenterImpl(this);
//        if (type.equals("discovery")) {
//            presenterImpl.getDiscovery(anchor, true);
//        } else {
//            presenterImpl.getDiscovery(anchor, false);
//        }
    }

    private void getData() {
        if (type.equals("circle")) {
            presenterImpl.getDiscovery(anchor, true);
        } else {
            presenterImpl.getDiscovery(anchor, false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        isRefresh = true;
        anchor = "0";
        presenterImpl = new DiscoveryPresenterImpl(this);
        if (type.equals("circle")) {
            presenterImpl.getDiscovery(anchor, true);
        } else {
            presenterImpl.getDiscovery(anchor, false);
        }

        if(!"circle".equals(type)){
            if (TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
                if ((!"circle".equals(type)) && (App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).getBoolean("default_should_show_notice", true))) {
                    notice_layout.setVisibility(View.VISIBLE);
                    App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).edit().putBoolean("default_should_show_notice", false).commit();
                }
            } else {
                if ((!"circle".equals(type)) && (App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).getBoolean(PreferenceUtils.GetUserIdHash() + "_should_show_notice", true))) {
                    notice_layout.setVisibility(View.VISIBLE);
                    App.GetInstance().getSharedPreferences("user_info_all", Context.MODE_PRIVATE).edit().putBoolean(PreferenceUtils.GetUserIdHash() + "_should_show_notice",false).commit();
                }
            }
        }

    }

    @Override
    public void showLoading() {
        if (isRefresh) {
            swipe_refresh.setRefreshing(true);
        }
    }

    @Override
    public void hideLoading() {
        swipe_refresh.setRefreshing(false);
    }

    @Override
    public void showError(String errMsg) {
//        Snackbar.make(swipe_refresh, errMsg, Snackbar.LENGTH_SHORT).show();
        MaterialDialog notice_dialog = new MaterialDialog.Builder(getActivity()).title("提示").positiveText("确认").cancelable(false).content(errMsg).build();
        notice_dialog.show();
    }

    @Override
    public void setDiscovery(DiscoveryBean beans) {
        if (beans != null) {
            if (beans.getStatus() == 0) {
                isLoading = false;
                if (isRefresh) {
                    anchor = "0";
                    entities.clear();
                }
                if (beans.getData() != null) {
                    if (beans.getData().getFeeds() != null && beans.getData().getFeeds().size() > 0) {
                        entities.addAll(beans.getData().getFeeds());
                        discoveryAdapter.setData(entities);
                        stopLoadMore = false;
                        no_data_desc.setVisibility(View.GONE);
                        isRefresh = false;
                    } else {
                        stopLoadMore = true;
                        if (isRefresh) {
                            no_data_desc.setVisibility(View.VISIBLE);
                            entities.clear();
                            discoveryAdapter.setData(new ArrayList<DiscoveryFeed>());
                            isRefresh = false;
                        }
                    }
                } else {
                    isLoading = false;
                    stopLoadMore = false;
                }
            } else {
                isLoading = false;
                stopLoadMore = false;
            }
        } else {
            isLoading = false;
            stopLoadMore = false;
        }
    }

    private void getPageDiscoveryFeeds(boolean refresh) {
        String anchor = "0";
        if (refresh)
            anchor = "0";
        else {
            if (entities.size() == 0) {
                anchor = "0";
            } else {
                anchor = entities.get(entities.size() - 1).getId() + "";
            }
        }
        if (!refresh) {
            if (stopLoadMore) {
                return;
            } else {
                stopLoadMore = true;
                isLoading = true;
            }
        } else {
            isLoading = true;
            stopLoadMore = true;
        }
        if (type.equals("circle")) {
            presenterImpl.getDiscovery(anchor, true);
        } else {
            presenterImpl.getDiscovery(anchor, false);
        }
    }

    public int getScrollY() {
        View c = content_list.getChildAt(0);
        if (c == null) {
            return 0;
        }
        int firstVisiblePosition = content_list.getFirstVisiblePosition();
        int top = c.getTop();
        return -top + firstVisiblePosition * c.getHeight();
    }
}
